package tech.hdis.framework.test;

import lombok.NonNull;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

/**
 * 针对Restful环境的Mock请求工厂
 *
 * @author 黄志文
 */
public class MockRestfulRequestFactory {
    /**
     * 构建POST请求
     *
     * @param url     请求URL
     * @param content 请求消息体
     * @return MockHttpServletRequestBuilder
     */
    public static MockHttpServletRequestBuilder post(@NonNull String url, Object content) {
        String jsonContent = "";
        if (content != null) {
            jsonContent = JSONUtils.toJson(content);
        }
        return MockMvcRequestBuilders
                .post(url)
                .content(jsonContent)
                .contentType(MediaType.APPLICATION_JSON)
                .characterEncoding("UTF-8")
                .accept(MediaType.APPLICATION_JSON);
    }

    /**
     * 构建DELETE请求
     *
     * @param url     请求URL
     * @param uriVars URL参数
     * @return MockHttpServletRequestBuilder
     */
    public static MockHttpServletRequestBuilder delete(@NonNull String url, Object... uriVars) {
        return MockMvcRequestBuilders
                .delete(url, uriVars)
                .accept(MediaType.APPLICATION_JSON);
    }

    /**
     * 构建GET请求
     *
     * @param url     请求URL
     * @param uriVars URL参数
     * @return MockHttpServletRequestBuilder
     */
    public static MockHttpServletRequestBuilder get(@NonNull String url, Object... uriVars) {
        return MockMvcRequestBuilders
                .get(url, uriVars)
                .accept(MediaType.APPLICATION_JSON);
    }

    /**
     * 构建PUT请求
     *
     * @param url     请求URL
     * @param content 请求消息体
     * @return MockHttpServletRequestBuilder
     */
    public static MockHttpServletRequestBuilder put(@NonNull String url, Object content) {
        String jsonContent = "";
        if (content != null) {
            jsonContent = JSONUtils.toJson(content);
        }
        return MockMvcRequestBuilders
                .put(url)
                .content(jsonContent)
                .contentType(MediaType.APPLICATION_JSON)
                .characterEncoding("UTF-8")
                .accept(MediaType.APPLICATION_JSON);
    }
}
